package exam;
import java.util.LinkedList;
import java.util.Queue;

class ProducerConsumer {
    private static final int BUFFER_SIZE = 5;
    private final Queue<Integer> buffer = new LinkedList<>();
    private int count = 0;

    public synchronized void produce() throws InterruptedException {
        while (count == BUFFER_SIZE) {
            wait();
        }
        int item = (int) (Math.random() * 100);
        buffer.add(item);
        System.out.println("Produced: " + item);
        count++;
        notifyAll();
    }

    public synchronized void consume() throws InterruptedException {
        while (count == 0) {
            wait();
        }
        int item = buffer.poll();
        System.out.println("Consumed: " + item);
        count--;
        notifyAll();
    }

    public static void main(String[] args) {
        ProducerConsumer pc = new ProducerConsumer();

        Thread producerThread = new Thread(() -> {
            try {
                for (int i = 0; i < 15; i++) {
                    pc.produce();
                    Thread.sleep(100);
                }
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            }
        });

        Thread consumerThread = new Thread(() -> {
            try {
                for (int i = 0; i < 15; i++) {
                    pc.consume();
                    Thread.sleep(150);
                }
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            }
        });

        producerThread.start();
        consumerThread.start();
    }
}
